
package com.scalar.chiptrack.sales.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Address;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.sales.SalesPerson;
import com.scalar.chiptrack.sales.dao.CustomerDAO;
import com.scalar.chiptrack.sales.dao.NewCustomerDAO;
import com.scalar.chiptrack.sales.forms.AddNewSalesPersonForm;
import com.scalar.chiptrack.users.User;


public class AddNewSalesPersonAction extends ChipTrackAction {

    private static final String ACTION_NAME = "/addNewSalesPerson.do" ;  // Added by Basha (08/08/2003)

    private ArrayList allsalespersons = new ArrayList();
    private String salesperson = null;
    private ArrayList allregions = new ArrayList();

    public ActionForward execute (ActionMapping mapping,
                                      ActionForm form,
                                      HttpServletRequest request,
                                      HttpServletResponse response)
                                     throws Exception {

        HttpSession session = request.getSession();


             User user = (User)session.getAttribute (SessionKeys.USER_KEY);

             if (user == null)
             {
                session.setAttribute (SessionKeys.SOURCE_PAGE_KEY, ACTION_NAME + "?" + request.getQueryString());
                return (mapping.findForward ("login"));
             }


		HashMap errors = new HashMap();
		request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

		HashMap info = new HashMap();
		request.setAttribute (SessionKeys.INFO_MESSAGES, info);


		AddNewSalesPersonForm subform=(AddNewSalesPersonForm) form;
		String action = request.getParameter("action");
        //int customerId = Integer.parseInt(request.getParameter("customerId"));
        //allsalespersons = CustomerDAO.getAllSalesPersonsWithActions(customerId);
        allsalespersons = NewCustomerDAO.getAllSalesPersonsWithActions();
        allregions = CustomerDAO.getAllRegions() ;
        request.setAttribute( "regions", allregions );
        request.setAttribute("salesPersons", allsalespersons);

		// Modified by Sarada on 3rd Feb 2004 to get all salespersons of that customer id

		if ("disable".equalsIgnoreCase(request.getParameter("salesPersonstatus")) == true)
		{
			String salesPersonToDelete = request.getParameter("salesPerson");
			//System.out.println("salesPersonToDelete  "+salesPersonToDelete);

			/*if ((salesPersonToDelete != null) && (salesPersonToDelete.trim().length() != 0))
			{
				try {
					// Modified by Sarada on 3rd Feb 2004 to disable salespersons of that customer id
					CustomerDAO.deleteSalesPerson( salesPersonToDelete , customerId );
					info.put (salesPersonToDelete + " has been disabled", null);
				}
				catch (ScalarException se)
				{
					se.printStackTrace ();
					errors.put ("Internal Server Error", "Could not delete \"" + salesPersonToDelete + "\"");
				}
			}*/
            int salesPersonId = 0;
            try{
                salesPersonId = Integer.parseInt( request.getParameter("salesPersonId") );
            }catch( NumberFormatException ignore ){

            }
            try{
                NewCustomerDAO.deactivateSalesPerson( salesPersonId, 1 ); //here deactivated is set to 1
			    info.put (salesPersonToDelete + " has been disabled", null);
            }
            catch (ScalarException se)
            {
                se.printStackTrace ();
                errors.put ("Internal Server Error", "Could not delete \"" + salesPersonToDelete + "\"");
            }
		}

		else if ("activate".equalsIgnoreCase(request.getParameter("salesPersonstatus")) == true)
		{
		     String salesPersonToActivate = request.getParameter("salesPerson");
		  /*if ((salesPersonToActivate != null) && (salesPersonToActivate.trim().length() != 0))
		  {
		    try
		    {
			    // Modified by Sarada on 3rd Feb 2004 to enable  salespersons of that customer id
		      CustomerDAO.activateSalesPerson ( salesPersonToActivate , customerId );
		      info.put (salesPersonToActivate + " has been activated", null);
		    }
		    catch (ScalarException se)
		    {
		      se.printStackTrace ();
		      errors.put ("Internal Server Error", "Could not activate \"" + salesPersonToActivate + "\"");
		    }*/
            int salesPersonId = 0;
            try{
                salesPersonId = Integer.parseInt( request.getParameter("salesPersonId") );
            }catch( NumberFormatException ignore ){

            }
            try{
                NewCustomerDAO.deactivateSalesPerson( salesPersonId, 0 );//here deactivated is set to 0
			    info.put (salesPersonToActivate + " has been activated", null);
		    }
            catch (ScalarException se)
		    {
		      se.printStackTrace ();
		      errors.put ("Internal Server Error", "Could not activate \"" + salesPersonToActivate + "\"");
		    }
		}
        else if( "loadSalesPerson".equalsIgnoreCase( action ) )
        {
            //String salesPersonToLoad = request.getParameter("salesPerson");
            //SalesPerson salesperson = CustomerDAO.getSalesPersonDetails( null, salesPersonToLoad, customerId );
            int salesPersonId = 0;
            try{
                salesPersonId = Integer.parseInt( request.getParameter("salesPersonId") );
            }catch( NumberFormatException ignore ){

            }

            SalesPerson salesperson = NewCustomerDAO.getSalesPersonDetails( null, salesPersonId );
            Address address = salesperson.getAddress();

            //subform.setNewSalesPerson( salesPersonToLoad );

            subform.setNewSalesPerson( salesperson.getSalesPerson() );
            subform.setOldSalesPerson( salesperson.getSalesPerson() );
            subform.setSalesPersonId( salesperson.getSalesPersonId() );
            subform.setSalesPercent( salesperson.getSalesPercent() );
            subform.setRegionId( salesperson.getRegionId() );
            subform.setSalesAckMail( salesperson.isSalesAckMail() );
            subform.setQuoteAckMail( salesperson.isQuoteAckMail() );
            subform.setShipAlerts( salesperson.isShipAlerts() );
            if ( address != null )
            {
                subform.setAddress1( address.getAddress1() );
                subform.setAddress2( address.getAddress2() );
                subform.setAddress3( address.getAddress3() );
                subform.setAddress4( address.getAddress4() );
                subform.setCity( address.getCity() );
                subform.setState( address.getState() );
                subform.setZipCode( address.getZipCode() );
                subform.setCountry( address.getCountry() );
                subform.setPhoneNumber( address.getPhoneNumber() );
                subform.setFaxNumber( address.getFaxNumber() );
                subform.setCellNumber( address.getCellNumber());
                subform.setEmail( address.getEmail() );
            }
        }
        else if ( "editSalesPerson".equalsIgnoreCase( action ) )
        {
			String newsalesperson = request.getParameter("newSalesPerson");
            String oldsalesperson = request.getParameter("oldSalesPerson");
            int salesPersonId = 0;
            int regionId = 0;

            try{
                salesPersonId = Integer.parseInt( request.getParameter("salesPersonId") );
                //regionId = Integer.parseInt( subform.getRegion() );
            }catch( NumberFormatException ignore ){

            }
            regionId = subform.getRegionId();

            boolean success = false;
            boolean insert  = false;
            boolean temp = false;

			if((newsalesperson == null) || (newsalesperson.trim().length() == 0)) {
				errors.put ( ERROR_CUSTOMER_INVALID_SALES_PERSON, null );
				return (mapping.findForward ("success"));
			}
            //SalesPerson salesperson = CustomerDAO.getSalesPersonDetails( null, oldsalesperson, customerId );
            SalesPerson salesperson = NewCustomerDAO.getSalesPersonDetails( null, salesPersonId );

            //allsalespersons = CustomerDAO.getAllSalesPersonsWithActions(customerId);
            allsalespersons = NewCustomerDAO.getAllSalesPersonsWithActions();
			int allsalespersonsSize = allsalespersons.size();
			SalesPerson  existingsalesperson = new  SalesPerson();

			for (int j=0; j<allsalespersonsSize; j++)
			{
				existingsalesperson =(SalesPerson)allsalespersons.get(j);
				String salespersonname = existingsalesperson.getSalesPerson();

				if( (newsalesperson != null) && (salespersonname != null) )
				{
					if ( !newsalesperson.equalsIgnoreCase(oldsalesperson) && newsalesperson.trim().equalsIgnoreCase(salespersonname) )
					{
						temp= true;
						break;
					}
				}
			}//for end

			if (temp == true) {
				errors.put ( newsalesperson +" " + ERROR_CUSTOMER_REP_ALREADY_EXISTS, null );
				return (mapping.findForward ("success"));
			}

            int addressId = -1 ;
            if ( salesperson.getAddress() != null )
            {
                addressId = salesperson.getAddress().getAddressId();
            }
            DBTransaction dbTransaction = null;
			try {
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
                if ( addressId > 0 )
                {
                    insert = false;
                }
                else
                {
                    insert = true;
                }
                /*addressId = CustomerDAO.insertAddress(dbTransaction, addressId,
                                            subform.getAddress1(),
                                            subform.getAddress2(),
											subform.getAddress3(),
											subform.getAddress4(),
                                            subform.getCity(),
                                            subform.getState(),
                                            subform.getZipCode(),
                                            subform.getCountry(),
                                            subform.getPhoneNumber(),
                                            subform.getFaxNumber(),
                                            subform.getEmail(),
                                            null, subform.getCellNumber(), insert , CustomerDAO.getCustomerNumber( dbTransaction, customerId ), null, null );*/
                //Commented this for there is no Customer id avilable here so setting the customer number to null
                /*addressId = CustomerDAO.insertAddress(dbTransaction, addressId,
                                            subform.getAddress1(),
                                            subform.getAddress2(),
											subform.getAddress3(),
											subform.getAddress4(),
                                            subform.getCity(),
                                            subform.getState(),
                                            subform.getZipCode(),
                                            subform.getCountry(),
                                            subform.getPhoneNumber(),
                                            subform.getFaxNumber(),
                                            subform.getEmail(),
                                            null, subform.getCellNumber(), insert , null, null, null );*/

                //Commmented By Phani. There is no Need to save Sales Persons Address into Great Plains.
                Address address = new Address();
                address.setAddressId( addressId );
                address.setAddress1( subform.getAddress1() );
                address.setAddress2( subform.getAddress2() );
                address.setAddress3( subform.getAddress3() );
                address.setAddress4( subform.getAddress4() );
                address.setCity( subform.getCity() );
                address.setState( subform.getState() );
                address.setZipCode( subform.getZipCode() );
                address.setCountry( subform.getCountry() );
                address.setPhoneNumber( subform.getPhoneNumber() );
                address.setFaxNumber( subform.getFaxNumber() );
                address.setEmail( subform.getEmail() );
                address.setCellNumber( subform.getCellNumber() );
                addressId = NewCustomerDAO.saveAddressIntoCT( dbTransaction, address );

                //CustomerDAO.updateSalesPerson (dbTransaction, newsalesperson, customerId, addressId, oldsalesperson );
                NewCustomerDAO.updateSalesPerson (dbTransaction, salesPersonId, newsalesperson, addressId, subform.getSalesPercent(), regionId, subform.isSalesAckMail(), subform.isQuoteAckMail(), subform.isShipAlerts() );
                subform.reset( mapping,request );
				info.put ( INFO_SALES_PERSON_SUCCESSFULLY_STORED, null );
				success = true;
			}
			catch (ScalarException se) {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				se.printStackTrace();
			}
            finally
            {
                if( success == true)
                {
                    dbTransaction.commit();
                }
                else
                {
                    dbTransaction.rollback();
                }
            }
        }
		if("insertSalesPerson".equalsIgnoreCase(action))
		{
			//region = addregionform.getNewRegion();
			salesperson = request.getParameter("newSalesPerson");
            float salesPercent = subform.getSalesPercent() ;
			boolean success = false;
			boolean temp = false;
            int addressId = -1 ;

			if((salesperson == null) || (salesperson.trim().length() == 0)) {
				errors.put ( ERROR_CUSTOMER_INVALID_SALES_PERSON, null );
				return (mapping.findForward ("success"));
			}
			//allsalespersons = CustomerDAO.getAllSalesPersonsWithActions(customerId);
            allsalespersons = NewCustomerDAO.getAllSalesPersonsWithActions();
			int allsalespersonsSize = allsalespersons.size();
			SalesPerson  salesPerson = new  SalesPerson();

			for (int j=0; j<allsalespersonsSize; j++)
			{
				salesPerson =(SalesPerson)allsalespersons.get(j);
				String salespersonname = salesPerson.getSalesPerson();
				// System.out.println("salespersonname  "+salespersonname);
				if( (salesperson != null) && (salespersonname != null) )
				{
					if (salesperson.trim().equalsIgnoreCase(salespersonname))
					{
						temp= true;
						break;
					}
				}
			}//for end

			if (temp == true) {
				errors.put ( salesperson +" " + ERROR_CUSTOMER_REP_ALREADY_EXISTS, null );
                //subform.setNewSalesPerson("");
				return (mapping.findForward ("success"));
			}
            DBTransaction dbTransaction = null;
			try {
				// Modified by Sarada on 3rd Feb 2004 to insert salespersons of that customer id
                dbTransaction = DBTransaction.getInstance();
                dbTransaction.begin();
                /*int addressId = SalesOrderDAO.saveShippingAddress(dbTransaction,
                                            subform.getAddress1(),
                                            subform.getAddress2(),
											subform.getAddress3(),
											subform.getAddress4(),
                                            subform.getCity(),
                                            subform.getState(),
                                            subform.getZipCode(),
                                            subform.getCountry(),
                                            subform.getPhoneNumber(),
                                            subform.getFaxNumber(),
                                            subform.getEmail(),
					                        "",
					                        subform.getCellNumber(), CustomerDAO.getCustomerNumber( dbTransaction, customerId ) );*/
                //Commented this for there is no Customer id avilable here so setting the customer number to null

                /*int addressId = SalesOrderDAO.saveShippingAddress(dbTransaction,
                                            subform.getAddress1(),
                                            subform.getAddress2(),
											subform.getAddress3(),
											subform.getAddress4(),
                                            subform.getCity(),
                                            subform.getState(),
                                            subform.getZipCode(),
                                            subform.getCountry(),
                                            subform.getPhoneNumber(),
                                            subform.getFaxNumber(),
                                            subform.getEmail(),
					                        "",
					                        subform.getCellNumber(), null ); */

                //CustomerDAO.insertSalesPerson (dbTransaction, salesperson, customerId, addressId);

                //Commmented By Phani. There is no Need to save Sales Persons Address into Great Plains.
                Address address = new Address();
                address.setAddressId( addressId );
                address.setAddress1( subform.getAddress1() );
                address.setAddress2( subform.getAddress2() );
                address.setAddress3( subform.getAddress3() );
                address.setAddress4( subform.getAddress4() );
                address.setCity( subform.getCity() );
                address.setState( subform.getState() );
                address.setZipCode( subform.getZipCode() );
                address.setCountry( subform.getCountry() );
                address.setPhoneNumber( subform.getPhoneNumber() );
                address.setFaxNumber( subform.getFaxNumber() );
                address.setEmail( subform.getEmail() );
                address.setCellNumber( subform.getCellNumber() );
                addressId = NewCustomerDAO.saveAddressIntoCT( dbTransaction, address );

                NewCustomerDAO.insertSalesPerson ( dbTransaction, salesperson, addressId, salesPercent, subform.getRegionId(), subform.isSalesAckMail(), subform.isQuoteAckMail(), subform.isShipAlerts());
                subform.reset( mapping,request );
				info.put ( INFO_SALES_PERSON_SUCCESSFULLY_STORED, null );
				success = true;
			}
			catch (ScalarException se) {
				errors.put ( ERROR_MESSAGE_CONTACT_SYS_ADMN, null );
				//errors.put ("Internal Server Error", "Could not cancel packingslip (" + packingSlipForm.getLabel() + ")");
				se.printStackTrace();
			}
            finally
            {
                if( success == true)
                {
                    dbTransaction.commit();
                }
                else
                {
                    dbTransaction.rollback();
                }
            }
		}
        //allsalespersons = CustomerDAO.getAllSalesPersonsWithActions(customerId);
        allsalespersons = NewCustomerDAO.getAllSalesPersonsWithActions();
        request.setAttribute("salesPersons",allsalespersons);
        return (mapping.findForward ("success"));
    }

}
